package service

import (
	"RestaurantApp/dao"
	"RestaurantApp/model"
	"encoding/json"
	"github.com/wonderivan/logger"
	"strconv"
	"time"
)

const Time_Duration = time.Minute * 5

type GoodsService struct {
}

func (this *GoodsService) GetGoodsByShopId(shopId int) []model.Goods {

	goodsDao := dao.GoodsDao{}
	goods := []model.Goods{}
	flag := this.goodsByShopIdIsCached(shopId)
	if flag {
		logger.Info("从redis缓存中获取食品信息")
		goods = this.getGoodsByShopIdCached(shopId)
		return goods
	}

	logger.Info("向MySQL数据库直查")
	goods = goodsDao.FindGoodsByShopId(shopId)

	this.setGoodsByShopIdCache(goods, shopId)

	return goods

}

//  使得key更加富有意义
func (this *GoodsService) getGoodsByShopIdCachedName(shopId int) string {
	return "goods_in_" + strconv.Itoa(shopId)
}

func (this *GoodsService) getGoodsByShopIdCached(shopId int) []model.Goods {
	key := this.getGoodsByShopIdCachedName(shopId)
	val, err := model.RedisClient.Get(key).Result()
	if err != nil {
		logger.Error(err.Error())
		return nil
	}
	//TODO error应该往上抛
	goods := []model.Goods{}
	err = json.Unmarshal([]byte(val), &goods)
	if err != nil {
		logger.Error(err.Error())
	}
	return goods

}

func (this *GoodsService) setGoodsByShopIdCache(goods []model.Goods, shopId int) {
	key := this.getGoodsByShopIdCachedName(shopId)
	data, err := json.Marshal(goods)
	if err != nil {
		logger.Error(err.Error())

	}
	err = model.RedisClient.Set(key, data, Time_Duration).Err()
	if err != nil {
		logger.Error(err.Error())
	}

}

func (this *GoodsService) goodsByShopIdIsCached(shopId int) bool {
	key := this.getGoodsByShopIdCachedName(shopId)
	val, err := model.RedisClient.Get(key).Result()
	if err != nil {
		logger.Error(err.Error())
		return false
	}
	if len(val) == 0 {
		logger.Error(err.Error())
		return false
	}
	return true
}
